package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.GuideImageSrc;
import com.letv.whatslive.model.convert.GuideImageSrcConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/12/30.
 */
@Repository
public class GuideImageSrcDAO extends BaseDAO{
    protected String collectionName = "guideImageSrc";
    private static final Logger logger = LoggerFactory.getLogger(GuideImageSrcDAO.class);
    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public GuideImageSrc getGuideImageSrcById(Long id){
        BasicDBObject query = new BasicDBObject();
        GuideImageSrc guideImageSrc = new GuideImageSrc();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            guideImageSrc = GuideImageSrcConvert.castDBObjectToGuideImageSrc(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return guideImageSrc;
    }
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("_id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("_id")));
            }
            if (params.get("exclusive_id") != null) {
                query.put("_id", new BasicDBObject("$ne", ObjectUtils.toLong(params.get("exclusive_id"))));
            }
            if (params.get("picType") != null) {
                query.put("picType", ObjectUtils.toInteger(params.get("picType")));
            }
            if (params.get("createTime") != null) {
                query.put("createTime", ObjectUtils.toLong(params.get("createTime")));
            }
            if (params.get("updateTime") != null) {
                query.put("updateTime", ObjectUtils.toLong(params.get("updateTime")));
            }
            if (params.get("startTime") != null) {
                query.put("startTime", ObjectUtils.toLong(params.get("startTime")));
            }
            if (params.get("endTime") != null) {
                query.put("endTime", ObjectUtils.toLong(params.get("endTime")));
            }
            if (params.get("showTime") != null) {
                query.put("showTime", ObjectUtils.toLong(params.get("showTime")));
            }
//
            if (params.get("picName") != null) {
                query.put("picName", ObjectUtils.toString(params.get("picName")));
            }
            if (params.get("picUrl") != null) {
                query.put("picUrl", ObjectUtils.toString(params.get("picUrl")));
            }
            if (params.get("isOpen") != null) {
                query.put("isOpen", ObjectUtils.toInteger(params.get("isOpen")));
            }
        }
        return query;
    }

    public List<GuideImageSrc> getAllGuideImageSrcByParams(Map<String, Object> params){
        List<GuideImageSrc> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                GuideImageSrc guideImageSrc = GuideImageSrcConvert.castDBObjectToGuideImageSrc(dbObject);
                result.add(guideImageSrc);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    public List<GuideImageSrc> getGuideImageSrcListByParams(Map<String, Object> params, Integer start, Integer limit) {
        List<GuideImageSrc> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                GuideImageSrc guideImageSrc = GuideImageSrcConvert.castDBObjectToGuideImageSrc(dbObject);
                result.add(guideImageSrc);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Long countProgramByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    public void deleteGuideImageSrcByParams(Long id){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", id);
        this.dbCollection.remove(query);
    }

    public GuideImageSrc saveGuideImageSrc(GuideImageSrc guideImageSrc) {
        try {
            guideImageSrc.setId(getAutoIncrementId());
            DBObject dbo = GuideImageSrcConvert.castGuideImageSrcToDBObject(guideImageSrc);
            WriteResult wr = this.dbCollection.insert(dbo);
            return guideImageSrc;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    public Boolean updateGuideImageSrc(GuideImageSrc guideImageSrc) {
        DBObject queryCondition = new BasicDBObject();
        Long guideImageSrcId = guideImageSrc.getId();
        if(guideImageSrcId==null)
            return false;
        queryCondition.put("_id", guideImageSrcId); // 用来确定要修改的文档
        DBObject setValue = GuideImageSrcConvert.castGuideImageSrcToDBObject(guideImageSrc);
        //剔除主键修改
        if (setValue.containsKey("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
        return true;
    }

    public List<GuideImageSrc> getInvalidImageSrcListByParams(Map<String, Object> params, Map<String, Object> orders) {

        List<GuideImageSrc> result = Lists.newArrayList();

        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = new BasicDBObject();

            // 是否开启
            if (params.get("isOpen") != null) {

                query.put("isOpen", ObjectUtils.toInteger(params.get("isOpen")));
            }

            Long now = System.currentTimeMillis();
            query.put("startTime", new BasicDBObject("$lte", now));
            query.put("endTime", new BasicDBObject("$gte", now));

            BasicDBObject order = getOrderParams(orders);
            DBCursor cur = this.dbCollection.find(query).sort(order);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                GuideImageSrc guideImageSrc = GuideImageSrcConvert.castDBObjectToGuideImageSrc(dbObject);
                result.add(guideImageSrc);
            }
        } catch (Exception e) {

            logger.error("getInvalidImageSrcListByParams error: ", e);
        }
        return result;
    }

    /**
     * 获取排序的BasicDBObject对象
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {

        BasicDBObject order = new BasicDBObject();

        if(orders != null && orders.size() > 0){

            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        } else {

            //默认按照创建时间排序
            order.append("createTime", -1);
        }

        return order;
    }
}
